package com.ezjie.ielts.db;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.ezjie.ielts.core.helper.AppDataBaseHelper;
import com.ezjie.ielts.model.SubjectDetail;

public class SubjectInfoDB {

	private static AppDataBaseHelper dbHelper;
	private SQLiteDatabase db;

	public SubjectInfoDB(Context context) {
		dbHelper = AppDataBaseHelper.getInstance(context);
	}

	// 查找科目
	public synchronized List<SubjectDetail> query(int type) {
		db = dbHelper.getReadableDatabase();

		List<SubjectDetail> lists = new ArrayList<SubjectDetail>();

		String sql = "select * from " + AppDataBaseHelper.SUBJECTS;
		Cursor cursor = db.rawQuery(sql, null);
		while (cursor.moveToNext()) {
			SubjectDetail info = new SubjectDetail();
			info.classify_id = cursor.getString(1);
			info.class_name = cursor.getString(2);
			info.class_name_en = cursor.getString(3);
			info.type = cursor.getInt(4);
			info.class_type = cursor.getString(5);
			info.num = cursor.getInt(6);
			if (info.type == type) {
				lists.add(info);
			}
		}
		cursor.close();
		db.close();

		return lists;
	}

	// 删除科目
	public synchronized void delete() {
		db = dbHelper.getWritableDatabase();

		String sql = "delete from " + AppDataBaseHelper.SUBJECTS;
		db.execSQL(sql);
		db.close();
	}

	// 更新科目
	public synchronized void update() {
		db = dbHelper.getWritableDatabase();

		String sql = "update " + AppDataBaseHelper.SUBJECTS + " set class_type= ? ";
		db.execSQL(sql, new Object[] { 1 });
		db.close();
	}

	/**
	 * 插入科目
	 * 
	 */
	public synchronized void insert(SubjectDetail subInfo) {
		db = dbHelper.getWritableDatabase();

		// db.beginTransaction();
		String sql = "insert into " + AppDataBaseHelper.SUBJECTS
				+ " (classify_id,class_name,class_name_en,type,class_type,num) " + "values(?,?,?,?,?,?)";
		db.execSQL(sql, new Object[] { subInfo.classify_id, subInfo.class_name, subInfo.class_name_en, subInfo.type,
				subInfo.class_type, subInfo.num });
		db.close();
	}

	/**
	 * 更新科目
	 * 
	 */
	public synchronized void replaceInto(List<SubjectDetail> subInfos) {
		db = dbHelper.getWritableDatabase();

		for (int i = 0; i < subInfos.size(); i++) {
			String sql = "replace into " + AppDataBaseHelper.SUBJECTS
					+ " (classify_id,class_name,class_name_en,type,class_type,num) " + "values(?,?,?,?,?,?)";
			db.execSQL(sql, new Object[] { subInfos.get(i).classify_id, subInfos.get(i).class_name,
					subInfos.get(i).class_name_en, subInfos.get(i).type, subInfos.get(i).class_type,
					subInfos.get(i).num });
		}

		db.close();
	}

}
